package pac

import (
	"fmt"
	"net"
	"os"
	"os/exec"
	"path/filepath"
	"slgw_web/serial/util"
	"syscall"
	"time"

	models "openzbox.com/frame/echo/models/sl_gw01"
)

func Test1() {
	fmt.Println("1")
	// Get the absolute path of the current executable
	executable, err := os.Executable()
	if err != nil {
		fmt.Println("获取可执行文件路径失败:", err)
		return
	}

	// Start a new process using the current executable
	cmd := exec.Command(executable)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	err = cmd.Start()
	if err != nil {
		fmt.Println("启动项目出错:", err)
		return
	}
	fmt.Println("2")
	// Terminate the current process
	os.Exit(0)

}
func Test2() {
	fmt.Println("执行重启命令...")
	// 获取项目的根目录
	rootDir, err := os.Getwd()
	if err != nil {
		fmt.Println("获取项目根目录失败:", err)
		return
	}

	// 构建重启脚本的完整路径
	restartScript := filepath.Join(rootDir, "restart.bat") //restart.sh
	// 执行重启脚本
	cmd := exec.Command(restartScript)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	// 使用 syscall.Exec 将当前进程替换为重启脚本
	err2 := cmd.Start()
	if err2 != nil {
		fmt.Println("启动重启脚本出错:", err2)
		os.Exit(1)
	}
	syscall.Exec(os.Args[0], os.Args, os.Environ())
}

// 重启项目
func RestartProject1() {

	fmt.Println("重启项目...")
	go func() {
		cmdStop := exec.Command("taskkill", "/F", "/IM", "main.exe")
		errStop := cmdStop.Run()
		if errStop != nil {
			fmt.Println("关闭当前程序出错:", errStop)
			os.Exit(1)
		}
	}()
	cmd := exec.Command("go", "run", "main.go")
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	err := cmd.Run()
	if err != nil {
		fmt.Println("启动项目出错:", err)
	}
	fmt.Println("项目已退出，重新启动...")

}

// 软重启TCP
func RestartTCPSoft(connold net.Conn) {
	time.Sleep(10 * time.Second)
	devices := util.DeviceInfo
	for i, item := range devices {
		if item.Conn == connold {
			//找到对应的conn，重新连接
			connold.Close()
			conn, err := net.Dial("tcp", item.IP+":"+item.PORT)
			if err != nil {
				util.Error(item.Name + "tcp重连错误:" + err.Error())
				continue
			} else {
				util.Error(item.Name + "tcp重连成功")
				devices[i].Conn = conn
			}

		}
	}
}

// 重启tcp连接
func RestartTcp(sb models.DeviceInfo) models.DeviceInfo {

	StopTimer(sb.DeviceInfoID + util.Task1)
	StopTimer(sb.DeviceInfoID + util.Task2)
	StopTimer(sb.DeviceInfoID + util.Task4)
	//重新连接TCP
	conn, err := net.Dial("tcp", sb.IP+":"+sb.PORT)
	if err != nil {
		// 连接的时候出现错误
		//判断是否已连接
		util.Error(sb.Name + " 重启tcp连接错误:" + err.Error())
		RestartTcp(sb)
	} else {
		sb.Conn = conn
		sbcopy := sb
		TcpC(sbcopy) //重新连接
		return sbcopy
	}
	return sb
}
func Reboot() {
	exe := "reboot"
	cmd := exec.Command("sh", "-c", exe)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	err := cmd.Run()
	if err != nil {
		util.Error("重启命令执行失败" + err.Error())
	}
}
